/**
 * All Rights Reserved , Copyright (C) 2020 , 青岛鼎信通讯股份有限公司
 * <p>
 * MeetManageController
 * 会议管理
 * <p>
 * 修改纪录
 * 2020-08-14 版本：1.0 wanghongwei 创建。
 *
 * @version 版本：1.0
 * @author 作者：wanghongwei
 * 创建日期：2020-08-14
 */

package com.topscomm.meet.controller;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.topscomm.base.pojo.BasePermissionManageEntity;
import com.topscomm.base.service.IBasePermissionManageService;
import com.topscomm.basic.util.SQLAdapter;
import com.topscomm.cbo.service.ICboItemDetailsService;
import com.topscomm.meet.MeetSystemConst;
import com.topscomm.meet.MeetSystemConst.MeetLauchOrgTypeEnum;
import com.topscomm.meet.MeetSystemConst.MeetPersonTypeEnum;
import com.topscomm.meet.MeetSystemConst.MeetSignStateEnum;
import com.topscomm.meet.MeetSystemConst.MeetStateEnum;
import com.topscomm.meet.controller.auto.MeetManageControllerAuto;
import com.topscomm.meet.dto.SelectUsers;
import com.topscomm.meet.pojo.MeetManageEntity;
import com.topscomm.meet.pojo.MeetPersonRecordEntity;
import com.topscomm.meet.pojo.MeetRecordEntity;
import com.topscomm.meet.pojo.MeetTypeManageEntity;
import com.topscomm.meet.service.*;
import com.topscomm.pub.util.BaseUtil;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.StringBufferProxy;
import com.topscomm.pub.util.StringUtil;
import com.topscomm.pub.vo.Page;
import com.topscomm.pub.vo.Query;
import com.topscomm.pub.vo.ResponseResult;
import com.topscomm.tap.common.ParameterCache;
import org.apache.commons.collections.CollectionUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.function.UnaryOperator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author: wanghongwei
 * @date: 2020-08-14
 * @description:会议管理Controller
 * @modify:
 */
@RestController
@RequestMapping("meet/meetManage")
public class MeetManageController extends MeetManageControllerAuto implements IMeetManageController {
    @Autowired
    private IMeetTypeManageService meetTypeManageService;
    @Autowired
    private IBasePermissionManageService basePermissionManageService;
    @Autowired
    private IMeetRecordService meetRecordService;
    @Autowired
    private IMeetPersonRecordService meetPersonRecordService;
    @Autowired
    private IMeetRoomApplyService meetRoomApplyService;
    @Autowired
    private ICboItemDetailsService cboItemDetailsService;
    @Autowired
    private IMeetManageHistoryService meetManageHistoryService;

    private static final String RecordIsEnabled = "recordisenabled";

    private static final String CanShare = "canshare";

    private static final String NoTokenFlag = "NoToken";

    /**
     * @param paraMap
     * @return
     * @author: wanghongwei
     * @date: 2020-08-14
     * @description:转换出查询SQL语句
     * @modify:
     */
    @Override
    protected String spellListSql(Map<String, Object> paraMap) {
        StringBufferProxy sql = new StringBufferProxy();

        //处理多参传递
        UnaryOperator<String> handleMultiParam = (value -> new ArrayList<>(Arrays.asList(value.split(","))).stream().map(s -> "'" + s + "'").collect(Collectors.joining(",")));
        String usercode;
        //区分非鉴权接口
        if (!ConvertUtil.convertToBoolean(paraMap.get(NoTokenFlag))) {
            usercode = this.getUserBean().getUser().getCode();
        } else {
            //网关非鉴权接口默认传入参数
            usercode = ConvertUtil.convertToString(paraMap.get("usercode"));
            if (usercode.isEmpty()) {
                throw new IllegalArgumentException("缺少usercode参数");
            }
        }
        sql.appendSingle(" 1=1 ");
        if (paraMap.containsKey("qry_name")) {
            String value = paraMap.get("qry_name").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and (name like '%{0}%'  or keywords like '%{1}%')", value, value);
        }
        this.service.appendSql(paraMap, sql, "qry_peroidtaskid", " and peroidtaskid = '{0}' ", value -> value);
        this.service.appendSql(paraMap, sql, "qry_usercode", " and usercode = '{0}' ", value -> value);
        this.service.appendSql(paraMap, sql, "qry_meettypeid", " and meettypeid = '{0}' ", value -> value);
        this.service.appendSql(paraMap, sql, "qry_meetnum", " and meetnum = '{0}' ", value -> value);
        this.service.appendSql(paraMap, sql, "qry_state", " and state = '{0}' ", value -> value);
        this.service.appendSql(paraMap, sql, "qry_sourcetype", " and sourcetype = '{0}' ", value -> value);
        this.service.appendSql(paraMap, sql, "qry_sourceid", " and sourceid = '{0}' ", value -> value);
        this.service.appendSql(paraMap, sql, "qry_sourceapp", " and sourceapp = '{0}' ", value -> value);
        this.service.appendSql(paraMap, sql, "qry_sourceids", " and sourceid in ({0}) ", handleMultiParam);
        if (paraMap.containsKey("qry_begindatetime")) {// 查询的开始时间
            String value = paraMap.get("qry_begindatetime").toString();
            if (!StringUtil.isEmpty(value)) {
                // 若传参不包含时分秒则拼接 00:00:00
                if (value.indexOf(":") >= 0) {
                    sql.appendSingle(" and endtime >= {0} ", SQLAdapter.toDateLong(value));
                } else {
                    sql.appendSingle(" and endtime >= {0} ", SQLAdapter.toDateLong(value + " 00:00:00"));
                }
            }
        }
        if (paraMap.containsKey("qry_enddatetime")) {// 查询的结束时间
            String value = paraMap.get("qry_enddatetime").toString();
            if (!StringUtil.isEmpty(value)) {
                // 若传参不包含时分秒则拼接 00:00:00
                if (value.indexOf(":") >= 0) {
                    sql.appendSingle(" and begintime <= {0} ", SQLAdapter.toDateLong(value));
                } else {
                    sql.appendSingle(" and begintime <= {0} ", SQLAdapter.toDateLong(value + " 23:59:59"));
                }
            }
        }
        String qry_teamid = ConvertUtil.convertToString(paraMap.get("qry_teamid"));
        String qry_deptcode = ConvertUtil.convertToString(paraMap.get("qry_deptcode"));
        if (qry_teamid.length() > 0 && qry_deptcode.length() > 0) {
            sql.appendSingle(
                    " and ((launchorgtype='{0}' and launchorgindex = '{1}') or (launchorgtype='{2}' and launchorgindex like '{3}%'))",
                    MeetLauchOrgTypeEnum.Team, qry_teamid, MeetLauchOrgTypeEnum.Dept, qry_deptcode);
        } else if (qry_teamid.length() > 0) {// 团队
            sql.appendSingle(" and launchorgtype='{0}' and launchorgindex = '{1}'", MeetLauchOrgTypeEnum.Team,
                    qry_teamid);
        } else if (qry_deptcode.length() > 0) {// 部门
            sql.appendSingle(" and launchorgtype='{0}' and launchorgindex like '{1}%'", MeetLauchOrgTypeEnum.Dept,
                    qry_deptcode);
        }
        if (paraMap.containsKey("qry_isall")) {
            String value = paraMap.get("qry_isall").toString();
            String[] manageParams = {"','", "manageusercodes", "','"};
            if (value.equals("0")) { // 查询创建者
                sql.appendSingle(" and (usercode = '{0}' or  ({1}) like '%{2}%') ",
                        usercode, SQLAdapter.concat(manageParams),
                        "," + usercode + ",");
            } else if (value.equals("1")) { // 查询可以看所有的会议

            }
        }
        if (paraMap.containsKey("qry_typeselect")) {// 类型选择
            String value = paraMap.get("qry_typeselect").toString();
            if (value.equals(MeetPersonTypeEnum.Attend)) {// 我参会的
                String[] manageParams = {"','", "manageusercodes", "','"};
                String typeCastMeetID = SQLAdapter.toInt(MeetPersonRecordEntity.FieldMeetid);
                sql.appendSingle(
                        " and (id in (select {0} from meetpersonrecord where usercode='{1}' " +
                                "union SELECT id FROM MeetManage WHERE usercode = '{2}' " +
                                "union SELECT id FROM MeetManage WHERE ({3}) like '%{4}%')) and state in ({5})",
                        typeCastMeetID, usercode, usercode,
                        SQLAdapter.concat(manageParams), "," + usercode + ",",
                        MeetStateEnum.Publish + "," +MeetStateEnum.SubmitChange);
            } else { // 查询所有的已发布的
                sql.appendSingle(" and state in ({0})", MeetStateEnum.Publish + "," +MeetStateEnum.SubmitChange);
            }
        }
        if (paraMap.containsKey("qry_launchuser")) {
            boolean isName = false;
            String value = paraMap.get("qry_launchuser").toString();
            if (!StringUtil.isEmpty(value)) {
                isName = value.codePoints().anyMatch(codepoint -> Character.UnicodeScript.of(codepoint) == Character.UnicodeScript.HAN);
                if (isName) {
                    sql.appendSingle(" and {0} like '{1}%'", MeetManageEntity.FieldLaunchusername, value);
                } else {
                    sql.appendSingle(" and {0} = '{1}'", MeetManageEntity.FieldLaunchusercode, value);
                }
            }
        }
        return sql.toString();
    }

    /**
     * @param paraMap
     * @return
     * @author: wanghongwei
     * @date: 2020-08-14
     * @description:转换出查询SQL语句
     * @modify:
     */
    @Override
    @GetMapping(value = "/refList")
    public ResponseResult<Object> refList(@RequestParam(required = false) Map<String, Object> paraMap) {
        return super.refList(paraMap);
    }

    /**
     * @param paraMap
     * @return
     * @description:
     * @author: donghang
     * @date: 2020年11月10日下午4:16:58
     * @modify:
     */
    @Override
    @DeleteMapping(value = "/delete")
    public ResponseResult<Object> delete(@RequestBody(required = false) Map<String, Object> paraMap) {
        try {
            paraMap = BaseUtil.decodeSecureMap(paraMap);
            String ids = ConvertUtil.convertToString(paraMap.get("ids"));
            this.service.deleteByIds(ids);
            // 删除可能有的会议室申请记录
            StringBufferProxy whereSql = new StringBufferProxy();
            whereSql.appendSingle(" sourcetype = '{0}' and sourceid = {1} ",
                    MeetManageEntity.tableName, paraMap.get("ids"));
            this.meetRoomApplyService.deleteByWhere(whereSql.toString());
            return ResponseResult.ok("删除成功");
        } catch (Exception ex) {
            return handleControllerException(ex);
        }
    }

    /**
     * 重写加载页面,需要配置是否可以查看纪要、录音
     *
     * @param paraMap
     * @return
     * @description:
     * @author: donghang
     * @date: 2020年9月1日下午4:22:58
     * @modify:
     */
    @Override
    @GetMapping(value = "/load")
    public ResponseResult<Object> load(@RequestParam(required = false) Map<String, Object> paraMap) {
        try {
            String usercode = this.getUserBean().getUser().getCode();
            paraMap = BaseUtil.decodeSecureMap(paraMap);
            Map<String, Object> dataMap = this.service.queryMapById(ConvertUtil.convertToString(paraMap.get("id")));
            afterLoad(dataMap);
            // 查询会议类型上级节点
            String meetTypeId = ConvertUtil.convertToString(dataMap.get("meettypeid"));
            List<String> meetTypeList = new ArrayList<>();
            if (meetTypeId.length() > 0) {
                List<MeetTypeManageEntity> typeList = this.meetTypeManageService.queryByWhere("id=" + meetTypeId);
                if (typeList.size() == 1) {
                    if (typeList.get(0).getParentid() > 0) {
                        meetTypeList.add(ConvertUtil.convertToString(typeList.get(0).getParentid()));
                    }
                }
                meetTypeList.add(meetTypeId);
            }
            dataMap.put("selectmeettypelist", meetTypeList);
            // 如果是查询页面,并且记录创建者非当前登录用户，则需要添加权限
            if (MeetSystemConst.MeetTaskSourceType.MeetSearch
                    .equals(ConvertUtil.convertToString(paraMap.get("operatetype")))
                    && (!ConvertUtil.convertToString(dataMap.get("usercode")).equals(usercode))) {
                // 查询纪要、录音权限
                this.setAccess(paraMap, dataMap);
            } else {
                dataMap.put(MeetPersonTypeEnum.Attend, true);
                dataMap.put(MeetPersonTypeEnum.Record, true);
                dataMap.put(MeetPersonTypeEnum.Audio, true);
            }
            // 判断当前人员是否参与人员、是否需要签到
            StringBufferProxy sql = new StringBufferProxy();
            sql.appendSingle("meetid='{0}' and usercode='{1}'", dataMap.get("id"),
                    usercode);
            List<MeetPersonRecordEntity> meetPersonList = meetPersonRecordService.queryByWhere(sql.toString());
            dataMap.put("needsign", false);
            if (meetPersonList.size() > 0) {
                dataMap.put(MeetPersonTypeEnum.Attend, true);
                Boolean isCanSign = this.service.isCanSign(ConvertUtil.convertToString(dataMap.get("id")));
                if (meetPersonList.get(0).getSignstate() == MeetSignStateEnum.NoSign && isCanSign) {
                    dataMap.put("needsign", true);
                }
            } else {
                dataMap.put(MeetPersonTypeEnum.Attend, false);
            }
            // 参会人员设置，纪要、录音都可看
            if (dataMap.containsKey(MeetPersonTypeEnum.Attend)
                    && ConvertUtil.convertToBoolean(dataMap.get(MeetPersonTypeEnum.Attend)) == true) {
                dataMap.put(MeetPersonTypeEnum.Record, true);
                dataMap.put(MeetPersonTypeEnum.Audio, true);
            }
            // 控制录音权限和有效时间
            this.setRecordPermission(dataMap, usercode);
            // 加载会议室相关信息
            this.meetRoomApplyService.setMeetRoomData(dataMap);
            // 添加资料id
            List<MeetRecordEntity> recordEntities = this.meetRecordService
                    .queryByWhere(" meetid = " + ConvertUtil.convertToString(paraMap.get("id")));
            if (recordEntities.size() > 0 && recordEntities.get(0) != null) {
                dataMap.put("recordid", recordEntities.get(0).getId());
            }
            //处理会议号
            if (dataMap.containsKey(MeetManageEntity.FieldRemotemeetinfo)) {
                String remotemeetinfo = ConvertUtil.convertToString(dataMap.get(MeetManageEntity.FieldRemotemeetinfo));
                String third_remote_code = "";
                Pattern pattern = Pattern.compile("[0-9]{3}[ -][0-9]{3}[ -][0-9]{3}");
                Matcher matcher = pattern.matcher(remotemeetinfo);
                if (matcher.find()) {
                   third_remote_code = matcher.group(0).replace(" ","").replace("-","");
                }
                dataMap.put("remoteMeetCode",third_remote_code);
            }
            //如果是发布变更中 && 会议创建 则展示历史版本数据
            if (ConvertUtil.convertToInt(dataMap.get("state")) == MeetStateEnum.SubmitChange && MeetSystemConst.MeetTaskSourceType.MeetSearch
                    .equals(ConvertUtil.convertToString(paraMap.get("operatetype")))){
                List<Map<String, Object>> historyList = meetManageHistoryService.queryMapByWhere(" meetid=" + ConvertUtil.convertToString(paraMap.get("id")) + " and valid=1");
                if (historyList.size() > 0) {
                    for (String key : dataMap.keySet()) {
                        if (historyList.get(0).containsKey(key) && !"id".equals(key)) {
                            dataMap.put(key, historyList.get(0).get(key));
                        }
                    }
                    dataMap.put("historyid", historyList.get(0).get("id"));
                }
            }

            return ResponseResult.ok(dataMap);
        } catch (Exception ex) {
            return handleControllerException(ex);
        }
    }

    /**
     * @description: 控制录音权限和有效时间
     * @author: chengengwei
     * @date: 2021-05-25
     * @modify:
     */
    private void setRecordPermission(Map<String, Object> dataMap, String usercode) {
        // 若用户为会议创建者或会议秘书，则拥有录音权限
        if (ConvertUtil.convertToString(dataMap.get("usercode")).equals(usercode) || ConvertUtil
                .convertToString(dataMap.get(MeetManageEntity.FieldManageusercodes)).contains(usercode)) {
            dataMap.put(MeetPersonTypeEnum.CanRecord, true);
            // 添加查看二维码的权限
            dataMap.put("showqrcode", true);
        } else {
            // 判断记录的权限记录表中拥有录音权限的人员中是否有当前账户
            long meetId = ConvertUtil.convertToLong(dataMap.get("id"));
            StringBufferProxy sqlWhere = new StringBufferProxy();
            sqlWhere.appendSingle(" sourcetype = '{0}' and sourceid = '{1}' and sourceflag = '{2}' ",
                    MeetManageEntity.tableName, meetId, MeetPersonTypeEnum.CanRecord);
            List<BasePermissionManageEntity> basePermissionManageList = basePermissionManageService
                    .queryByWhere(sqlWhere.toString());
            if (CollectionUtils.isEmpty(basePermissionManageList)) {
                // 没有权限记录，则没有权限
                dataMap.put(MeetPersonTypeEnum.CanRecord, false);
            } else {
                // 存在权限记录
                BasePermissionManageEntity basePermissionManageEntity = basePermissionManageList.get(0);
                String shareObjects = basePermissionManageEntity.getShareobjects();
                if (shareObjects.contains(usercode)) {
                    // 权限记录中包含当前账户
                    dataMap.put(MeetPersonTypeEnum.CanRecord, true);
                } else {
                    // 权限记录中不包含当前账户
                    dataMap.put(MeetPersonTypeEnum.CanRecord, false);
                }
            }
        }
        // 会议开始前多久可以录音，单位小时
        double beforeTime = ConvertUtil
                .convertToDouble(ParameterCache.getValue(MeetSystemConst.CanRecordForStart, "2"));
        // 会议结束后多久内可以录音，单位小时
        double afterTime = ConvertUtil
                .convertToDouble(ParameterCache.getValue(MeetSystemConst.CanRecordForEnd, "24"));
        // 有效范围起始时间点
        DateTime startTime = DateUtil.offsetMinute((Date) dataMap.get(MeetManageEntity.FieldBegintime),
                (int) (beforeTime * 60 * -1));
        // 有效范围结束时间点
        DateTime endTime = null;
        // 移动端快捷会议无结束时间
        if (dataMap.get(MeetManageEntity.FieldEndtime) != null) {
            endTime = DateUtil.offsetMinute((Date) dataMap.get(MeetManageEntity.FieldEndtime),
                    (int) (afterTime * 60));
        }
        // 当前时间
        Date now = new Date();
        // 判断当前是否在录音有效时间范围内
        if (now.after(startTime) && (endTime == null || (endTime != null && now.before(endTime)))) {
            dataMap.put(RecordIsEnabled, true);
        } else {
            dataMap.put(RecordIsEnabled, false);
        }
        // 判断是否能分享
        if (now.before((Date) dataMap.get(MeetManageEntity.FieldBegintime))
                && ConvertUtil.convertToBoolean(dataMap.get(MeetPersonTypeEnum.Attend))) {
            dataMap.put(CanShare, true);
        } else {
            dataMap.put(CanShare, false);
        }
    }

    /**
     * 设置文件、录音授权
     *
     * @param paraMap
     * @param dataMap
     * @description:
     * @author: donghang
     * @date: 2020年12月1日下午1:35:57
     * @modify:
     */
    private void setAccess(Map<String, Object> paraMap, Map<String, Object> dataMap) {
        // 初始化
        dataMap.put(MeetPersonTypeEnum.Record, false);
        dataMap.put(MeetPersonTypeEnum.Audio, false);
        List<MeetRecordEntity> recordList = meetRecordService.queryByWhere("meetid=" + dataMap.get("id"));
        // 会议纪要发布后，查看录音、纪要文件的附加权限
        if (recordList.size() == 1 && recordList.get(0).getState() == MeetStateEnum.Publish) {
            MeetRecordEntity meetRecordEntity = recordList.get(0);
            // 纪要文件是否可看
            long recordId = meetRecordEntity.getId();
            String sqlWhere = this.basePermissionManageService.createUserShareCondition(this.getUserBean(), true,
                    "begintime");
            StringBufferProxy sql = new StringBufferProxy();
            if (sqlWhere.length() > 0) {
                sql.appendSingle(" sourcetype='{0}' and sourceid ='{1}' and sourceflag='{2}' and ({3}) ",
                        MeetRecordEntity.tableName, recordId, MeetPersonTypeEnum.Record, sqlWhere);
            }
            if (this.meetRecordService.queryMapByWhere(sql.toString(), "queryPermissionList").size() != 0) {
                dataMap.put(MeetPersonTypeEnum.Record, true);
            }
            // 录音文件是否可看
            sqlWhere = this.basePermissionManageService.createUserShareCondition(this.getUserBean(), true, "begintime");
            sql.clear();
            if (sqlWhere.length() > 0) {
                sql.appendSingle(" sourcetype='{0}' and sourceid ='{1}' and sourceflag='{2}' and ({3}) ",
                        MeetRecordEntity.tableName, recordId, MeetPersonTypeEnum.Audio, sqlWhere);
            }
            if (this.meetRecordService.queryMapByWhere(sql.toString(), "queryPermissionList").size() != 0) {
                dataMap.put(MeetPersonTypeEnum.Audio, true);
            }
            // 属于参会人员或缺席人员可以查看录音或纪要
            String attendUsers = "," + ConvertUtil.convertToString(meetRecordEntity.getAttendusercodes()) + ",";
            String absentUsers = "," + ConvertUtil.convertToString(meetRecordEntity.getAbsentusercodes()) + ",";
            if (attendUsers.contains("," + this.getUserBean().getUser().getCode() + ",")
                    || absentUsers.contains("," + this.getUserBean().getUser().getCode() + ",")) {
                dataMap.put(MeetPersonTypeEnum.Record, true);
                dataMap.put(MeetPersonTypeEnum.Audio, true);
            }
        }
    }

    /**
     * 保存数据
     *
     * @param paraMap
     * @return
     * @description:
     * @author: donghang
     * @date: 2020年11月3日下午12:49:47
     * @modify:
     */
    @RequestMapping(value = "/save", method = {RequestMethod.POST, RequestMethod.PUT})
    public ResponseResult<Object> save(@RequestBody(required = false) Map<String, Object> paraMap) {
        try {
            MeetManageEntity meetManageEntity = this.service.save(paraMap, this.getUserBean());
            Map<String, Object> meetManagMap = meetManageEntity.convertToMap();
            this.meetRoomApplyService.setMeetRoomData(meetManagMap);
            return ResponseResult.ok(meetManagMap);
        } catch (Exception ex) {
            return handleControllerException(ex);
        }
    }

    /**
     * 会议发布
     *
     * @param paraMap
     * @return
     * @description:
     * @author: donghang
     * @date: 2020年11月3日上午8:48:36
     * @modify:
     */
    @Override
    @PostMapping(value = "/publish")
    public ResponseResult<Object> publish(@RequestBody(required = false) Map<String, Object> paraMap) {
        MeetManageEntity meetManageEntity = this.service.publishMeet(paraMap, this.getUserBean());
        return ResponseResult.ok("发布成功", meetManageEntity);
    }

    /**
     * @param paraMap
     * @return
     * @description: 会议作废
     * @author: donghang
     * @date: 2020年9月1日下午4:22:58
     * @modify:
     */
    @Override
    @PostMapping(value = "/cancel")
    public ResponseResult<Object> cancel(@RequestBody(required = false) Map<String, Object> paraMap) {
        try {
            this.service.cancelMeet(paraMap, this.getUserBean());
            return ResponseResult.ok("作废成功");
        } catch (Exception ex) {
            return handleControllerException(ex);
        }
    }

    @PostMapping(value = "/stopSign")
    public ResponseResult<Object> stopSign(@RequestBody(required = false) Map<String, Object> paraMap) {
        BaseUtil.decodeSecureMap(paraMap);
        this.service.stopSign(ConvertUtil.convertToString(paraMap.get("meetid")), this.getUserBean());
        return ResponseResult.ok("操作成功，该会议已停止签到，可以上传会议纪要");
    }

    /**
     * 重写接口,给手机端只传列表长度
     *
     * @param paraMap
     * @return
     * @description:
     * @author: chengengwei
     * @date: 2021-01-21
     * @modify:
     */
    @GetMapping({"/getTotalCount"})
    public ResponseResult<Object> getTotalCount(@RequestParam(required = false) Map<String, Object> paraMap) {
        try {
            paraMap = BaseUtil.decodeSecureMap(paraMap);
            Query query = new Query(paraMap);
            paraMap.put(NoTokenFlag, false);
            String sqlWhere = this.spellListSql(paraMap);
            int totalCount = this.service.getCount(sqlWhere);
            // 手机端只获取总数
            Map<String, Object> resultData = new HashMap<>();
            if (paraMap.containsKey("only_count")) {
                String value = paraMap.get("only_count").toString();
                if (!StringUtil.isEmpty(value) && "1".equals(value)) {
                    resultData.put("totalCount", totalCount);
                }
            }
            return ResponseResult.ok(resultData);
        } catch (Exception var) {
            return this.handleControllerException(var);
        }
    }

    /**
     * 重写接口,给手机端只传列表长度
     *
     * @param paraMap
     * @return
     * @description:
     * @author: chengengwei
     * @date: 2021-01-21
     * @modify:
     */
    @GetMapping({"/getTotalCountNoToken"})
    public ResponseResult<Object> getTotalCountNoToken(@RequestParam(required = false) Map<String, Object> paraMap) {
        try {
            BaseUtil.decodeSecureMap(paraMap);
            paraMap.put(NoTokenFlag, true);
            StringBufferProxy sqlWhere = new StringBufferProxy();
            sqlWhere.appendSingle(this.spellListSql(paraMap));
            //如果不包含开始 结束日期参数 则默认赋值
            if (!paraMap.containsKey("qry_begindatetime") && !paraMap.containsKey("qry_enddatetime")) {
                DateTime now = new DateTime();
                sqlWhere.appendSingle(" and endtime >= {0}  ",SQLAdapter.toDateLong(now.toString()));
                sqlWhere.appendSingle(" and begintime <= {0}", SQLAdapter.toDateLong(now.offset(DateField.DAY_OF_MONTH, 7).toString()));
            }
            int totalCount = this.service.getCount(sqlWhere.toString());
            // 手机端只获取总数
            Map<String, Object> resultData = new HashMap<>();
            if (paraMap.containsKey("only_count")) {
                String value = paraMap.get("only_count").toString();
                if (!StringUtil.isEmpty(value) && "1".equals(value)) {
                    resultData.put("totalCount", totalCount);
                }
                DateTime now = new DateTime();
            }
            return ResponseResult.ok(resultData);
        } catch (Exception var) {
            return this.handleControllerException(var);
        }
    }

    /**
     * @param paraMap
     * @return
     * @description:重写查询列表
     * @author: chengengwei
     * @date: 2019-2-22
     * @modify:
     */
    @Override
    @GetMapping(value = "/list")
    public ResponseResult<Object> list(@RequestParam(required = false) Map<String, Object> paraMap) {
        paraMap = BaseUtil.decodeSecureMap(paraMap);
        Query query = new Query(paraMap);
        paraMap.put(NoTokenFlag, false);
        String sqlWhere = this.spellListSql(paraMap);
        int totalCount = this.service.getCount(sqlWhere);
        List<Map<String, Object>> tempList = null;
        if (query.getPageSize() > 0) {
            //根据发起人按拼音排序
            query.setSidx(query.getSidx().contentEquals(MeetManageEntity.FieldLaunchusername) ? "NLSSORT(LAUNCHUSERNAME,'NLS_SORT=SCHINESE_PINYIN_M')" : query.getSidx());
            tempList = this.service.queryMapForPage(sqlWhere, query.getCurrentPage(), query.getPageSize(),
                    query.getSidx(), query.getSord());
        } else {
            tempList = this.service.queryMapByWhere(sqlWhere);
        }
        this.service.addMeetState(tempList);
        //如果是查询列表，替换发布变更中的信息
        if (paraMap.containsKey("qry_typeselect") && !StringUtil.isEmpty(paraMap.get("qry_typeselect").toString())) {
            this.service.replaceChangeMeetInfo(tempList);
        }
        this.service.addMeetState(tempList);
        Page page = new Page(tempList, totalCount, query.getPageSize(), query.getCurrentPage());
        return ResponseResult.ok(page);
    }

    @PostMapping(value = "list")
    public ResponseResult<Object> postList(@RequestBody(required = false) Map<String, Object> paraMap) {
        return this.list(paraMap);
    }

    @GetMapping(value = "/queryDataByTypeAndId")
    public ResponseResult<Object> queryDataByTypeAndId(@RequestParam(required = false) Map<String, Object> map) {
        try {
            Map<String, Object> resultMap = new HashMap<>();
            StringBufferProxy sql = new StringBufferProxy();
            sql.appendSingle("select * from {0} where id = {1}", ConvertUtil.convertToString(map.get("sourcetype")),
                    ConvertUtil.convertToString(map.get("id")));
            List<Map<String, Object>> resultList = this.service.selectExecute(sql.toString());
            if (resultList.size() > 0 && resultList.get(0) != null) {
                resultMap = resultList.get(0);
            }
            return ResponseResult.ok(resultMap);
        } catch (Exception e) {
            return handleControllerException(e);
        }
    }

    /**
     * @Description: 根据会议id查询参会人员
     * @Author: mengmeng
     * @Date: 2021/6/1 14:26
     * @Version: 1.0
     */
    @GetMapping(value = "/queryAttendUserByMeetId")
    public ResponseResult<Object> queryAttendUserByMeetId(@RequestParam(required = false) Map<String, Object> paraMap) {
        try {
            paraMap = BaseUtil.decodeSecureMap(paraMap);
            long meetId = ConvertUtil.convertToLong(paraMap.get("meetid"));
            List<Map<String, Object>> allAttendUsers = this.service.queryUserByMeetId(meetId);
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("attendusers", allAttendUsers);
            return ResponseResult.ok(resultMap);
        } catch (Exception e) {
            return handleControllerException(e);
        }
    }

    /**
     * @Description: 录音权限转让接口
     * @Author: mengmeng
     * @Date: 2021/6/1 16:04
     * @Version: 1.0
     */
    @PostMapping(value = "/transferRecordAuthority")
    public ResponseResult<Object> transferRecordAuthority(@RequestBody(required = false) Map<String, Object> paraMap) {
        try {
            paraMap = BaseUtil.decodeSecureMap(paraMap);
            long meetId = ConvertUtil.convertToLong(paraMap.get("meetid"));
            String userCode = ConvertUtil.convertToString(paraMap.get("users"));
            this.service.transferRecordAuthority(meetId, userCode);
            return ResponseResult.ok("转让权限成功");
        } catch (Exception e) {
            return handleControllerException(e);
        }
    }

    /**
     * @param
     * @return 参会相关信息
     * @description: 手机端扫码 查询会议信息 判断用户参会状态
     * @author xinfushuo
     * @date 2022/1/14
     * @modify
     */
    @GetMapping(value = "/queryAttendMeetFlag")
    public ResponseResult<Object> queryAttendMeetFlag(@RequestParam(required = false) Map<String, Object> paraMap) {
        try {
            paraMap = BaseUtil.decodeSecureMap(paraMap);
            String meetId = ConvertUtil.convertToString(paraMap.get("meetid"));
            boolean attendMeetFlag = this.service.judgeCurrentUserAttendMeet(meetId);
            boolean alreadySignedIn = meetPersonRecordService.isAlreadySigned(meetId, ConvertUtil.convertToString(paraMap.get("replaceusercode")));
            Map<String, Object> dataMap = this.service.queryMapById(meetId);
            dataMap.put("attendMeetFlag", attendMeetFlag);
            dataMap.put("alreadySignedIn", alreadySignedIn);
            return ResponseResult.ok(dataMap);
        } catch (Exception e) {
            return handleControllerException(e);
        }
    }

    /**
     * @description: 查询通过微前端集成创建的会议是否上传了会议纪要，如果存在
     * @author: chengengwei
     * @date: 2021-12-03
     * @modify:
     */
    @GetMapping(value = "/queryUploadedRecordOfMicro")
    public ResponseResult<Object> queryUploadedRecordOfMicro(@RequestParam(required = false) Map<String, Object> paraMap) {
        try {
            Boolean uploaded = this.service.queryUploadedRecordOfMicro(ConvertUtil.convertToString(paraMap.get("sourcetype")),
                    ConvertUtil.convertToLong(paraMap.get("sourceid")),
                    ConvertUtil.convertToString(paraMap.get("sourceapp")));
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("uploaded", uploaded);
            return ResponseResult.ok(resultMap);
        } catch (Exception ex) {
            return handleControllerException(ex);
        }
    }

    /**
     * 根据前端传参计算参会总人数
     *
     * @param users 前端参会人参数
     * @return 返回所选总人数
     * @throws
     * @author xinfushuo
     * @date 2022/9/22
     * @modify
     */
    @PostMapping
    @RequestMapping(value = "queryMeetPersonCount")
    public ResponseResult<Object> queryMeetPersonCount(@RequestBody SelectUsers users) {
        //将users转为map
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String, Object> map = objectMapper.convertValue(users, Map.class);
        List<Map<String, Object>> list = this.basePermissionManageService.getAllAttendUser(map);
        //返回总数
        return ResponseResult.ok(list.size());
    }

    @GetMapping
    @RequestMapping(value = "/getThirdPartyForwardInfo")
    public ResponseResult<Object> getThirdPartyForwardInfo() {
        List<Map<String, Object>> maplist = cboItemDetailsService.queryMap(new HashMap<>(), "queryThird");
        return ResponseResult.ok(maplist.stream().collect(Collectors.groupingBy(m -> m.get("instancetype"), Collectors.toList())));
    }

}
